package com.ugoodtech.mdcc.web.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.web.dto.DepartmentResponse;
import com.ugoodtech.mdcc.web.dto.JsonResponse;
import com.ugoodtech.mdcc.web.dto.LabelValue;
import com.ugoodtech.mdcc.web.dto.ServerResponse;
import com.ugoodtech.mdcc.web.pojo.vo.AllDepartmentListVO;
import com.ugoodtech.mdcc.web.service.DepartmentService;
import io.swagger.annotations.*;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(description = "部门管理")
@Controller
@RequestMapping("/department")
public class DepartmentController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(DepartmentController.class);

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private NationRepository nationRepository;

    @Autowired
    private BrandRepository brandRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private StationRepository stationRepository;

    /**
     * 添加一级部门
     *
     * @param code
     * @param name
     * @return
     */
    @ApiOperation("添加一级部门")
    @RequestMapping(value = "/addFirstDeparment", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse addFirstDeparment(@ApiParam("部门编号") @RequestParam("code") String code,
                                          @ApiParam("部门名称") @RequestParam("name") String name) {
        Department department = departmentRepository.selectDeparmentByCode(code, name);
        if (department != null) {
            return JsonResponse.successResponseWithData("抱歉，此部门编号或者名称已经被使用了");
        }
        department = new Department();
        department.setSerialNumber(code);
        department.setName(name);
        department.setType(0);
        departmentRepository.save(department);
        Map<String, Object> data = new HashMap<>();
        data.put("str", name);
        userLogService.addUserLog(this.getCurrentUser(), null, LogConstants.operate_type_add, LogConstants.business_type_department, null, data);
        return JsonResponse.successResponse();
    }

    @ApiOperation("添加次级部门")
    @RequestMapping(value = "/addChildDeparment", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse addChildDeparment(@ApiParam("部门编号") @RequestParam("code") String code,
                                          @ApiParam("部门名称") @RequestParam("name") String name,
                                          @ApiParam("上级部门id") @RequestParam("departmentId") Long departmentId,
                                          @ApiParam("维修站ID") @RequestParam(value = "stationIds", required = false) String stationIds) {
        Department department = departmentRepository.selectDeparmentByCode(code, name);
        if (department != null) {
            return JsonResponse.successResponseWithData("抱歉，此部门编号或者名称已经被使用了");
        }
        Department pranetDeparment = departmentRepository.findOne(departmentId);
        if (pranetDeparment == null) {
            return JsonResponse.successResponseWithData("抱歉，未找到上级部门");
        }
        department = new Department();
        department.setParent(pranetDeparment);
        department.setSerialNumber(code);
        department.setName(name);
        Department department1 = departmentRepository.findOne(departmentId);
        if (department1!=null && department1.getType()==100) {
            department.setType(1);
        }else {
            department.setType(0);
        }
        if (StringUtils.isNotEmpty(stationIds)) {
            String[] ids = stationIds.split(",");
            List<Station> stationList = new ArrayList<>();
            for (String id : ids) {
                if (StringUtils.isNotEmpty(id)) {
                    Station station = stationRepository.findOne(Long.valueOf(id));
                    if (station != null) {
                        stationList.add(station);
                    }
                }
            }
            department.setStationList(stationList);
        }
        departmentRepository.save(department);
        Map<String, Object> data = new HashMap<>();
        data.put("str", name);
        userLogService.addUserLog(this.getCurrentUser(), null, LogConstants.operate_type_add, LogConstants.business_type_department, null, data);
        return JsonResponse.successResponse();
    }


    @ApiOperation("部门列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = User.class)
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getAllDepartment(@ApiParam("用户ID") @RequestParam(value = "userId", required = false) Long userId,
                                         @ApiParam("姓名") @RequestParam(value = "username", required = false) String username,
                                         @ApiParam("部门关键字") @RequestParam(value = "description", required = false) String description,
                                         Pageable pageable) {
        isUserLogin();
        List<Department> departments = departmentService.getFirstDepartments();
        for (Department department : departments) {
            department = setDepartment(department);
            setChildren(department);
        }
        return JsonResponse.successResponseWithData(departments);
    }

    @ApiOperation("通过关键字与一级部门获取部门名称")
    @RequestMapping(value = "/getDepartmentByName", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getDepartmentByName(@ApiParam("用户ID") @RequestParam(value = "loginUserId") Long loginUserId,
                                            @ApiParam("一级部门ID") @RequestParam(value = "departmentId") Long departmentId,
                                            @ApiParam("部门名称关键字") @RequestParam(value = "departmentName", required = false) String departmentName) {
        Department partenDepartment = departmentRepository.findOne(departmentId);
        QDepartment qDepartment = QDepartment.department;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qDepartment.deleted.eq(false));
        builder.and(qDepartment.enabled.eq(true));
        builder.and(qDepartment.parent.id.eq(departmentId));
        if (StringUtils.isNotEmpty(departmentName)) {
            builder.and(qDepartment.name.like("%" + departmentName + "%"));
        }
        List<Department> departments = (List<Department>) departmentRepository.findAll(builder);
        for (Department department : departments) {
            department.setFirstDepartmentName(partenDepartment.getName());
        }
        partenDepartment.setChildren(departments);
//        for (Department department : departments) {
//            department = setDepartment(department);
//            setChildren(department);
//        }
        List<Department> departmentList = new ArrayList<>();
        departmentList.add(partenDepartment);
        return JsonResponse.successResponseWithData(departmentList);
    }

    /**
     *This URL is used for getting the "所属部门" list for adding staff
     */
    @RequestMapping(value = "/getAllDepartmentsList", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse getAllDepartmentsList(@RequestParam(value = "departmentType",required = false, defaultValue = "0") Integer departmentType,
                                                @RequestParam(value = "departmentName",required = false) String departmentName) throws Exception{
        isUserLogin();
        User currentUser = getCurrentUser();
        List<AllDepartmentListVO> allDepartmentListVoList = departmentService.getAllDepartmentsList(departmentType, departmentName,currentUser);
        return ServerResponse.success("获取所有部门列表成功",allDepartmentListVoList);
    }


    @ApiOperation("获取经销商部门列表")
    @RequestMapping(value = "/getDealersDepartment", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getDealersDepartment(@ApiParam("用户ID") @RequestParam(value = "userId", required = false) Long userId) {
        isUserLogin();
        List<Department> departments = departmentService.getChildDepartments(27L);
        for (Department department : departments) {
            department = setDepartment(department);
            setChildren(department);
        }
        return JsonResponse.successResponseWithData(departments);
    }

    public void setChildren(Department department) {
        List<Department> children = departmentService.getChildDepartments(department.getId());
        department.setChildren(children);
        for (Department cDepartment : children) {
            cDepartment.setFirstDepartmentName(department.getName());
            Department voDepartment = departmentRepository.findOne(cDepartment.getId());
            cDepartment = setDepartment(cDepartment);

            setChildren(cDepartment);
        }
    }

    private Department setDepartment(Department department) {
        if (department.getParent() != null) {
            department.setParentDepartmentId(department.getParent().getId());
        }
        if (null != department.getLeader()) {
            UserProfile userProfile = userProfileRepository.findByUserId(department.getLeader().getId());
            if (userProfile != null) {
                department.setLeaderName(userProfile.getRealName());
                if (StringUtils.isNotEmpty(userProfile.getSerialNumber())) {
                    department.setLeaderNum(userProfile.getSerialNumber());
                } else {
                    department.setLeaderNum("");
                }
            } else {
                department.setLeaderName("");
            }
        } else {
            department.setLeaderNum("");
            department.setLeaderName("");
        }
        return department;
    }

    @ApiOperation("编辑部门")
    @RequestMapping(value = "/editDepartment", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse editDepartment(
            @ApiParam("部门id") @RequestParam("departmentId") Long departmentId,
            @ApiParam("部门编号") @RequestParam("code") String code,
            @ApiParam("部门名称") @RequestParam("name") String name,
            @ApiParam("维修站ID") @RequestParam(value = "stationIds", required = false) String stationIds) {
        QDepartment qDepartment = QDepartment.department;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qDepartment.deleted.eq(false));
        builder.and(qDepartment.enabled.eq(true));
        builder.and(qDepartment.serialNumber.eq(code));
        builder.and(qDepartment.name.eq(name));
        Department department = departmentRepository.findOne(builder);
        if (department != null && !department.getId().equals(departmentId)) {
            return JsonResponse.errorResponseWithError("抱歉", "此部门编号或者名称已经被使用了");
        }
        department = departmentRepository.findOne(departmentId);
        if (department.getParent() == null) {
            return JsonResponse.errorResponseWithError("抱歉", "无法修改一级部门");
        }
        if (StringUtils.isNotEmpty(stationIds)) {
            String[] ids = stationIds.split(",");
            List<Station> stationList = new ArrayList<>();
            for (String id : ids) {
                if (StringUtils.isNotEmpty(id)) {
                    Station station = stationRepository.findOne(Long.valueOf(id));
                    if (station != null) {
                        stationList.add(station);
                    }
                }
            }
            department.setStationList(stationList);
        } else {
            department.setStationList(new ArrayList<Station>());
        }
        Map<String, Object> data = new HashMap<>();
        String desc = "";
        if (!code.equals(department.getSerialNumber())) {
            desc += "部门编号 :";
            desc += department.getSerialNumber() + "-->>" + code + ",";
        }

        if (!name.equals(department.getName())) {
            desc += "部门名称 :";
            desc += department.getName() + "-->>" + name + ",";
        }
        data.put("str", desc);
        department.setSerialNumber(code);
        department.setName(name);
        departmentRepository.save(department);
        userLogService.addUserLog(this.getCurrentUser(), null, LogConstants.operate_type_edit, LogConstants.business_type_department, null, data);
        return JsonResponse.successResponse();
    }

    @ApiOperation("删除部门")
    @RequestMapping(value = "/deleteDepartment", method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse deleteDepartment(
            @ApiParam("部门id") @RequestParam("departmentId") Long departmentId
    ) {
        List<Department> departmentList = departmentRepository.selectParentDeparmentL(departmentId);
        if (departmentList != null && departmentList.size() > 0) {
            return JsonResponse.errorResponseWithError("抱歉", "此部门有下级部门，无法删除");
        }
        Department parentDeparment = departmentRepository.findOne(departmentId);
        if (parentDeparment.getParent() == null) {
            return JsonResponse.errorResponseWithError("抱歉", "此部门是一级部门无法删除");
        }
        Department department = departmentRepository.findOne(departmentId);
        department.setDeleted(true);
        department.setEnabled(false);
        department.setParent(null);
        departmentRepository.save(department);
        Map<String, Object> data = new HashMap<>();
        data.put("str", department.getName());
        userLogService.addUserLog(this.getCurrentUser(), null, LogConstants.operate_type_delete, LogConstants.business_type_department, null, data);
        return JsonResponse.successResponse();
    }


    @ApiOperation("设定负责人")
    @RequestMapping(value = "/addDepartmentUser", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse addDepartmentUser(
            @ApiParam("部门Id") @RequestParam(value = "departmentId", required = false) Long departmentId,
            @ApiParam("员工号") @RequestParam(value = "userNo", required = false) String userNo,
            @ApiParam("负责人姓名") @RequestParam(value = "name", required = false) String name
    ) {
        Department department = departmentRepository.findOne(departmentId);
        if (null == department) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此部门");
        }
        if (StringUtils.isEmpty(userNo) && StringUtils.isEmpty(name)) {
            department.setLeader(null);
            departmentRepository.save(department);
            return JsonResponse.successResponse();
        }
        logger.info("查询此人是否存在");
        UserProfile userProfile = userProfileRepository.findBySerialNumberAndName(userNo, name);
        if (userProfile == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此管理员");
        }
        logger.info("判断此人是否在当前部门");
        Department hasDepartment = departmentRepository.findOne(departmentId);
        if (!userProfile.getDepartmentList().contains(hasDepartment)) {
            return JsonResponse.errorResponseWithError("抱歉", "此管理员不在当前部门");
        }
        Department leaderDeparment = departmentRepository.selectDeparmentLeader(userProfile.getUser().getId());
        if (leaderDeparment != null) {
            logger.info("判断此人是否是部门的负责人");
            if (leaderDeparment.getId().equals(departmentId)) {
                return JsonResponse.errorResponseWithError("抱歉", "此管理员已经负责此部门了");
            }
            return JsonResponse.errorResponseWithError("抱歉", "此管理员已经负责了别的部门：" + leaderDeparment.getTotalName());
        }
        logger.info("不是部门负责人，继续执行设定负责人操作");
        department.setLeader(userProfile.getUser());
        departmentRepository.save(department);
        Map<String, Object> data = new HashMap<>();
        data.put("str", userProfile.getRealName() + "(" + userProfile.getSerialNumber() + ")" + "==>" + hasDepartment.getTotalName());
        userLogService.addUserLog(this.getCurrentUser(), null, LogConstants.operate_type_add_department_user, LogConstants.business_type_department, null, data);
        return JsonResponse.successResponse();
    }

    @ApiOperation("部门下拉框")
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = User.class)
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "/comboList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse comboList() {
        isUserLogin();
        List<Department> departmentList = new ArrayList<>();
        List<Department> departments = departmentService.getFirstDepartments();
        for (Department department : departments) {
            departmentList.add(department);
            getChildren(department, departmentList);
        }
        System.out.println("departmentList.size()="+departmentList.size());
//        List<DeparmentDTO> comboData = new ArrayList<>();
//        for (Department department : departmentList) {
//            DeparmentDTO labelValue = new DeparmentDTO(department.getTotalName(), department.getId() + "",null!=department.getLeader().getId()?department.getLeader().getId()+"":"",department.getType());
//            comboData.add(labelValue);
//        }
        return JsonResponse.successResponseWithData(departmentList);
    }

    public void getChildren(Department department, List<Department> departmentList) {
        List<Department> children = departmentService.getChildDepartments(department.getId());
        for (Department cDepartment : children) {
            departmentList.add(cDepartment);
            getChildren(cDepartment, departmentList);
        }
    }


    @ApiOperation("获取一级部门")
    @RequestMapping(value = "/getFirstDeparments", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getFirstDeparments() {
        isUserLogin();
//        List<Department> departmentList = new ArrayList<>();
        List<Department> departments = departmentService.getFirstDepartments();
//        for (Department department : departments) {
//            departmentList.add(department);
//        }
//        List<Department> comboData = new ArrayList<>();
//        for (Department department : departmentList) {
//            DeparmentDTO labelValue = new DeparmentDTO(department.getTotalName(), department.getId() + "",null!=department.getLeader().getId()?department.getLeader().getId()+"":"",department.getType());
//            comboData.add(labelValue);
//        }
        return JsonResponse.successResponseWithData(departments);
    }


    @ApiOperation("获取子部门")
    @RequestMapping(value = "/getChildDeparments", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse getChildDeparments(Long deparmentId) {
        isUserLogin();
//        List<Department> departmentList = new ArrayList<>();
        List<Department> departments = departmentService.getChildDepartments(deparmentId);
//        for (Department department : departments) {
//            departmentList.add(department);
//        }
//        List<DeparmentDTO> comboData = new ArrayList<>();
//        for (Department department : departmentList) {
//            DeparmentDTO labelValue = new DeparmentDTO(department.getTotalName(), department.getId() + "",null!=department.getLeader().getId()?department.getLeader().getId()+"":"",department.getType());
//            comboData.add(labelValue);
//        }
        return JsonResponse.successResponseWithData(departments);
    }


    public List<LabelValue> getDepartMentUser(Long departmentId) {
        QUserProfile qUserProfile = QUserProfile.userProfile;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qUserProfile.deleted.eq(false));
        builder.and(qUserProfile.enabled.eq(true));
        builder.and(qUserProfile.departmentList.any().id.eq(departmentId));
        List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(builder);
        List<LabelValue> labelValueList = new ArrayList<>();
        for (UserProfile userProfile : userProfileList) {
            LabelValue labelValue = new LabelValue();
            labelValue.setLabel(userProfile.getUser().getId().toString());
            labelValue.setTitle(userProfile.getRealName());
            labelValueList.add(labelValue);
        }
        return labelValueList;
    }
    @ApiOperation("获取部门下的所有人")
    @RequestMapping(value = "/comboDepartmentUser", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse comboDepartmentUser() {
        QDepartment qDepartment = QDepartment.department;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qDepartment.deleted.eq(false));
        builder.and(qDepartment.enabled.eq(true));
        List<Department> departmentList = (List<Department>) departmentRepository.findAll(builder);
        List<DepartmentResponse> departmentResponseList = new ArrayList<>();
        for (Department department : departmentList) {
            DepartmentResponse response = new DepartmentResponse();
            response.setTitle(department.getTotalName());
            List<LabelValue> labelValues = getDepartMentUser(department.getId());
            response.setChildren(labelValues);
            response.setType(department.getType());
            departmentResponseList.add(response);
        }
        return JsonResponse.successResponseWithData(departmentResponseList);
    }

}
